<template>
  <div class="favorites-container">
    <div v-if="favorites.length === 0" class="no-favorites">
      暂无收藏题目
    </div>
    
    <div v-else class="favorites-list">
      <div v-for="item in favorites" :key="item.favoriteId || item.id" class="favorite-item">
        <div class="favorite-content">
          <p class="favorite-description">{{ item.content || item.questionContent || '暂无描述' }}</p>
          <div class="favorite-meta">
            <span class="favorite-date">收藏时间：{{ formatDate(item.createTime) }}</span>
            <span class="favorite-id">ID: {{ item.favoriteId || item.id }}</span>
          </div>
        </div>
        <div class="favorite-actions">
          <el-button type="primary" size="small" @click="viewDetail(item)">查看详情</el-button>
          <el-button type="danger" size="small" @click="removeFavorite(item.favoriteId || item.id)">取消收藏</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { useUserStore } from '../../../store/UserStore'
import axios from 'axios'

export default {
  name: 'UserFavorites',
  data() {
    return {
      favorites: [],
      userStore: useUserStore()
    }
  },
  methods: {
    async fetchFavorites() {
      try {
        const userId = this.userStore.getUserInfo?.userId
        if (!userId) {
          this.$message.warning('请先登录')
          return
        }
        
        const response = await axios.get(`http://localhost:8080/user_favorites_vo/listByUserId/${userId}`)
        // 假设接口返回的都是题目类型的收藏
        this.favorites = response.data
        
        // 打印收藏项数据，查看结构
        console.log('收藏列表数据:', this.favorites)
        if (this.favorites.length > 0) {
          console.log('第一个收藏项示例:', this.favorites[0])
        }
      } catch (error) {
        console.error('获取收藏列表失败:', error)
        this.$message.error('获取收藏列表失败')
      }
    },
    
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      const pad = n => n.toString().padStart(2, '0')
      return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
    },
    
    viewDetail(item) {
      // 跳转到FavoriteQuestion.vue组件
      this.$router.push({
        path: '/home/favorite-questions'
      })
    },
    
    async removeFavorite(id) {
      try {
        // 检查id是否存在
        if (!id) {
          console.error('收藏ID不存在')
          this.$message.error('收藏ID不存在，无法删除')
          return
        }
        
        await this.$confirm('确定要取消收藏吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        console.log('正在删除收藏，ID:', id) // 添加日志
        
        // 使用UserFavoritesController中的delete接口
        await axios.get(`http://localhost:8080/favorites/delete?id=${id}`)
        this.$message.success('取消收藏成功')
        this.fetchFavorites() // 重新获取收藏列表
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消收藏失败:', error)
          this.$message.error('取消收藏失败')
        }
      }
    }
  },
  mounted() {
    this.fetchFavorites()
  }
}
</script>

<style scoped>
.favorites-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  margin-top: 0 !important;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.no-favorites {
  text-align: center;
  color: #999;
  padding: 40px 20px;
  font-size: 16px;
}

.favorites-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.favorite-item {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.favorite-content {
  flex: 1;
}

.favorite-description {
  color: #666;
  margin-bottom: 10px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.favorite-meta {
  display: flex;
  gap: 20px;
  color: #999;
  font-size: 14px;
}

.favorite-type {
  background: #e6f7ff;
  color: #1890ff;
  padding: 2px 8px;
  border-radius: 4px;
}

.favorite-actions {
  display: flex;
  gap: 10px;
}

@media (max-width: 768px) {
  .favorite-item {
    flex-direction: column;
    gap: 15px;
  }
  
  .favorite-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>
